﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace CaseManagerLibrary.Socket
{
    public static class NetworkHelper
    {
        public static string GetLocalIP(Func<IPEndPoint, IPEndPoint, bool> testConnection = null, IPEndPoint tcpServerEP = null)
        {
            string ip = "";
            try
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress item in IpEntry.AddressList)
                {
                    if (item.AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (testConnection != null && tcpServerEP != null)
                        {
                            if (testConnection(null, tcpServerEP))
                            {
                                ip = item.ToString();
                                break;
                            }
                        }
                        else
                        {
                            ip = item.ToString();
                            break;
                        }
                    }
                }
            }
            catch { }

            return ip;
        }

        public static IPEndPoint GetLocalEndPoint(int port, Func<IPEndPoint, IPEndPoint, bool> testConnection = null, IPEndPoint tcpServerEP = null)
        {
            IPEndPoint ep = null;
            try
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress item in IpEntry.AddressList)
                {
                    if (item.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ep = new IPEndPoint(IPAddress.Parse(item.ToString()), port);

                        if (testConnection != null && tcpServerEP != null)
                        {
                            if (testConnection(ep, tcpServerEP))
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            catch { }

            return ep;
        }
    }
}
